package com.dqp.cslggroup.Features;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.*;
import androidx.appcompat.widget.AppCompatSeekBar;
import androidx.appcompat.widget.Toolbar;
import com.alibaba.fastjson.JSONObject;
import com.dqp.cslggroup.Api.schoolApi;
import com.dqp.cslggroup.Calendar.CalendarEventView;
import com.dqp.cslggroup.EventBus.MessageEvent;
import com.dqp.cslggroup.R;
import com.dqp.cslggroup.SmartTableInfo.dakaInfo;
import com.dqp.cslggroup.UI.BaseActivity;
import com.dqp.cslggroup.UI.ButtonAdapter;
import com.dqp.cslggroup.UI.DialogView;
import com.dqp.cslggroup.UI.MyApplication;
import com.dqp.cslggroup.Util.*;
import com.dqp.cslggroup.bean.avatar;
import com.dqp.cslggroup.newStudent;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;


public class Setting extends BaseActivity {
    private Uri uritempFile;
    private int lattice_length;
    private int course_jie;
    private int transparency;
    private int blur;
    private int timeSize;
    private static String[] permissions = {
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_CALENDAR,
            Manifest.permission.WRITE_CALENDAR,
            Manifest.permission.READ_EXTERNAL_STORAGE
    };

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.setting);
        EventBus.getDefault().register(this);
        Toolbar toolbar = findViewById(R.id.toolbar);
        toolbar.setTitle("");
        setSupportActionBar(toolbar);
        Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
        initCmp();
        initAppSeting();
        initApp();
        initWidget();
    }

    private void initCmp() {
        final Switch notThisWeek = findViewById(R.id.notThisWeek);
        Switch Weekends = findViewById(R.id.showWeekends);
        Switch Time = findViewById(R.id.showTime);
        Switch couples = findViewById(R.id.showCouples);
        Switch desktop = findViewById(R.id.desktopWallpaper);
        boolean isThisWeeks = SharedPreferencesUtil.getBooleanSp(this, "show", false);
        boolean showWeekends = SharedPreferencesUtil.getBooleanSp(this, "showWeekends", true);
        boolean showTime = SharedPreferencesUtil.getBooleanSp(this, "showTime", true);
        boolean showCouples = SharedPreferencesUtil.getBooleanSp(this, "showCouples", false);
        boolean showDesktopWallpaper = SharedPreferencesUtil.getBooleanSp(this, "showDesktopWallpaper", false);
        notThisWeek.setChecked(isThisWeeks);
        notThisWeek.setOnClickListener(v -> {
            SharedPreferencesUtil.putBooleanSp(this, "show", notThisWeek.isChecked());
            EventBus.getDefault().post(new MessageEvent("SubjectFragment", true));
        });
        Weekends.setChecked(showWeekends);
        Weekends.setOnClickListener(v -> {
            SharedPreferencesUtil.putBooleanSp(this, "showWeekends", Weekends.isChecked());
            EventBus.getDefault().post(new MessageEvent("SubjectFragment", true));
        });
        Time.setChecked(showTime);
        Time.setOnClickListener(v -> {
            SharedPreferencesUtil.putBooleanSp(this, "showTime", Time.isChecked());
            EventBus.getDefault().post(new MessageEvent("SubjectFragment", true));
        });
        couples.setChecked(showCouples);
        couples.setOnClickListener(v -> {
            if (couples.isChecked()) {
                SharedPreferencesUtil.putBooleanSp(this, "showCouples", true);
                ToastUtil.showToast("重启应用生效");
            } else {
                SharedPreferencesUtil.putBooleanSp(this, "showCouples", false);
            }
            EventBus.getDefault().post(new MessageEvent("MainActivity", 6));
        });
        desktop.setChecked(showDesktopWallpaper);
        desktop.setOnClickListener(v -> {
            if (desktop.isChecked()) {
                final com.dqp.cslggroup.UI.AlertDialog alertDialog = new com.dqp.cslggroup.UI.AlertDialog(Setting.this);
                alertDialog.builder();
                alertDialog.setGone()
                        .setTitle("跟随系统壁纸")
                        .setMsgGravity(false)
                        .setCancelable(false)
                        .setMsg("开启跟随系统壁纸后将会获取您手机桌面壁纸作为课程界面的壁纸，" +
                                "如果您的手机桌面壁纸过大，或手机壁纸为动态壁纸，将会导致应用壁纸获取失败，" +
                                "甚至会导致应用出现闪退的现象，请根据您的实际情况考虑该功能！")
                        .setPositiveButton("取消", R.color.colorAccent, v1 -> desktop.setChecked(false))
                        .setNegativeButton("开启", R.color.colorAccent, v1 -> {
                            SharedPreferencesUtil.putBooleanSp(this, "showDesktopWallpaper", true);
                            ToastUtil.showToast("重启应用生效");
                        }).show();
            } else {
                SharedPreferencesUtil.putBooleanSp(this, "showDesktopWallpaper", false);
                ToastUtil.showToast("取消系统跟随壁纸设置，重启应用生效");
            }
        });

    }

    @SuppressLint("InflateParams")
    public void initAppSeting() {
        String bg = SharedPreferencesUtil.getStringSp(this, "bg_path", null);
        if (bg == null) bg = "设置应用课表页面背景，默认使用桌面壁纸作为背景";
        com.dqp.cslggroup.UI.MyListView listView11 = findViewById(R.id.app_steing_list);
        List<dakaInfo> infos = new ArrayList<>();
        infos.add(new dakaInfo("清除数据", "清除应用数据库和SharedPreferences内所有数据"));
        infos.add(new dakaInfo("背景设置", bg));
        infos.add(new dakaInfo("背景模糊", "设置背景模糊(毛玻璃/磨砂)效果，半径范围0~25。部分类型图片无法被模糊处理会导致应用闪退！若出现闪退清空请前往设置清除本应用数据！"));
        infos.add(new dakaInfo("头像设置", "修改登录教务系统获取到的个人头像"));
        infos.add(new dakaInfo("账号管理", "绑定用户的信息门户账号、教务系统账号，已获取本应用的所有功能支持"));
        infos.add(new dakaInfo("还原背景", "初始化应用的背景设置，课表页面背景还原默认"));
        ButtonAdapter arrayAdapter = new ButtonAdapter(infos, Setting.this);
        listView11.setAdapter(arrayAdapter);
        listView11.setOnItemClickListener((adapterView, view, i, l) -> {
            switch (i) {
                case 0:
                    ToastUtil.showToast("长按清除！");
                    break;
                case 1:
                    if (EasyPermissions.hasPermissions(this, permissions)) {
                        Intent intent = new Intent(Intent.ACTION_PICK);
                        intent.setType("image/*");
                        startActivityForResult(intent, 1);
                    } else new AppSettingsDialog.Builder(this)
                            .setTitle("权限申请")
                            .setRationale("您没有授权应用所需的读写手机存储的相关权限，此功能无法运行。请打开应用设置以修改应用权限。")
                            .build().show();
                    break;
                case 2:
                    DialogView.seekBarDialog(this, "背景模糊", "高斯模糊", "r", (dialog, save, seekBar, seekBarDialog_length) -> {
                        seekBar.setOnSeekBarChangeListener(new AppCompatSeekBar.OnSeekBarChangeListener() {
                            @SuppressLint("SetTextI18n")
                            @Override
                            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                                blur = progress * 2;
                                if (blur >= 25) blur = 24;
                                seekBarDialog_length.setText(blur + "");
                            }

                            @Override
                            public void onStartTrackingTouch(SeekBar seekBar) {

                            }

                            @Override
                            public void onStopTrackingTouch(SeekBar seekBar) {

                            }
                        });
                        save.setOnClickListener(v -> {
                            SharedPreferencesUtil.putIntSp(this, "blur", blur);
                            dialog.dismiss();
                            EventBus.getDefault().post(new MessageEvent("MainActivity", 7));
                        });


                    });
                    break;
                case 3:
                    if (EasyPermissions.hasPermissions(this, permissions)) {
                        Intent intent = new Intent(Intent.ACTION_PICK);
                        intent.setType("image/*");
                        startActivityForResult(intent, 2);
                    } else new AppSettingsDialog.Builder(this)
                            .setTitle("权限申请")
                            .setRationale("您没有授权应用所需的读写读写手机存储的相关权限，此功能无法运行。请打开应用设置以修改应用权限。")
                            .build().show();
                    break;

                case 4:
//                    List<student> studentList = MyApplication.getDaoInstant().getStudentDao().loadAll();
//                    if (studentList.size() > 0) {
//                        final android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(Setting.this);
//                        view = LayoutInflater.from(Setting.this).inflate(R.layout.jxj_more, null);
//                        builder.setView(view);
//                        TextView title = view.findViewById(R.id.title);
//                        ListView listView1 = view.findViewById(R.id.list);
//                        title.setText("账号密码");
//                        Dialog dialog = builder.show();
//                        UiUtils.setDialogWindowAttr(dialog, Setting.this);
//                        Objects.requireNonNull(dialog.getWindow()).setBackgroundDrawableResource(android.R.color.transparent);
//                        String jwxtSno = SharedPreferencesUtil.getStringSp(this, "stuNum_JWXT", null);
//                        String libSno = SharedPreferencesUtil.getStringSp(this, "stuNum_lib", null);
//                        String zcSno = SharedPreferencesUtil.getStringSp(this, "stuNum_XSGZ", null);
//                        String jwxt = SharedPreferencesUtil.getStringSp(this, "password_JWXT", null);
//                        String lib = SharedPreferencesUtil.getStringSp(this, "password_lib", null);
//                        String zc = SharedPreferencesUtil.getStringSp(this, "password_XSGZ", null);
//                        student student = studentList.get(0);
//                        List<dakaInfo> list = new ArrayList<>();
//                        if (student.getXh().equals(jwxtSno)) list.add(new dakaInfo("教务系统", jwxt));
//                        if (student.getXh().equals(libSno)) list.add(new dakaInfo("图书系统", lib));
//                        if (student.getXh().equals(zcSno)) list.add(new dakaInfo("综测查询", zc));
//                        twoTextViewAdapter adapter = new twoTextViewAdapter(list, this);
//                        listView1.setAdapter(adapter);
//                    } else ToastUtil.showToast("无账户信息！");
                    UiUtils.startActivity(this, newStudent.class);
                    break;
                case 5:
                    ToastUtil.showToast("长按还原！");
                    break;
            }
        });

        listView11.setOnItemLongClickListener((parent, view, position, id) ->
        {
            if (position == 0) {
                dateUtil.deletData(Setting.this);
                EventBus.getDefault().post(new MessageEvent("MainActivity", 9));
                ToastUtil.showToast("清除完成！");

            }
            if (position == 5) {
                SharedPreferencesUtil.removeSp(this, "blur");
                CompressedBitmap.reSeting(this, "bg_path");
                EventBus.getDefault().post(new MessageEvent("MainActivity", 7));
                initAppSeting();
                initApp();
                initWidget();
                ToastUtil.showToast("还原完成！");
            }
            return true;
        });

    }

    public void initApp() {
        String xl = SharedPreferencesUtil.getStringSp(this, "xl", null);
        if (xl == null) xl = "自动获取校历数据并完成周数设置";
        String date = SharedPreferencesUtil.getStringSp(this, "Start_date", null);
        if (date == null) date = "用于计算当前周数,开学日期必须选择周一以确保周数计算的正确性！";
        com.dqp.cslggroup.UI.MyListView listView = findViewById(R.id.setting_app_list);
        List<dakaInfo> infos = new ArrayList<>();
        infos.add(new dakaInfo("自动设置周数", xl));
        infos.add(new dakaInfo("设置开学日期", date));
        infos.add(new dakaInfo("课程格子高度", "修改课表界面的课程格子高度，用户可根据自己的手机尺寸自定义"));
        infos.add(new dakaInfo("课程节数设置", "修改课表节数，范围0~15节"));
        infos.add(new dakaInfo("时间字体大小", "修改课表左侧节数内的时间字体大小，范围0~15sp"));
        infos.add(new dakaInfo("上课通知提醒", "将课程写入日程，将会在上课前收到日程提醒，写入后请自行检查日程以免出错"));
        infos.add(new dakaInfo("格子透明度设置", "修改课表界面的课程格子透明度"));
        ButtonAdapter arrayAdapter = new ButtonAdapter(infos, Setting.this);
        listView.setAdapter(arrayAdapter);
        listView.setOnItemClickListener((adapterView, view, i, l) -> {
            switch (i) {
                case 0:
                    com.dqp.cslggroup.UI.AlertDialog alertDialog = new com.dqp.cslggroup.UI.AlertDialog(this);
                    alertDialog.builder();
                    alertDialog.setGone()
                            .setTitle("设置周数")
                            .setMsg("重新获取校历数据以重新设置周数？")
                            .setNegativeButton("确定", R.color.colorAccent, v13 -> new Thread(() -> {
                                JSONObject jsonObject = schoolApi.schoolCalendar();
                                if (Result.jsonResultIsTure(jsonObject) && jsonObject.containsKey("starttime")) {
                                    SharedPreferencesUtil.putStringSp(this, "xl", jsonObject.getString("starttime"));
                                    EventBus.getDefault().post(new MessageEvent("Setting", 1));
                                    ToastUtil.showToast("✌周数设置成功！");
                                } else ToastUtil.showToast("🤦‍获取失败！");
                            }).start())
                            .setPositiveButton("删除", R.color.colorAccent, v14 -> {
                                SharedPreferencesUtil.removeSp(this, "xl");
                                initApp();
                                initWidget();
                                alertDialog.dismiss();
                            }).show();
                    break;
                case 1:
                    final android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(Setting.this);
                    @SuppressLint("InflateParams") View view1 = LayoutInflater.from(Setting.this).inflate(R.layout.data_select, null);
                    builder.setView(view1);
                    TextView title = view1.findViewById(R.id.title);
                    title.setText("开学日期（请选择周一）");
                    DatePicker datePicker = view1.findViewById(R.id.DatePicker);
                    TextView sub = listView.getChildAt(i).findViewById(R.id.setting_subtext);
                    Button save1 = view1.findViewById(R.id.btn_save);
                    Button btn_cancel1 = view1.findViewById(R.id.btn_cancel);
                    Dialog dialog1 = builder.show();
                    UiUtils.setDialogWindowAttr(dialog1, Setting.this);
                    Objects.requireNonNull(dialog1.getWindow()).setBackgroundDrawableResource(android.R.color.transparent);
                    save1.setOnClickListener(v1 -> {
                        int year = datePicker.getYear();
                        int month = datePicker.getMonth() + 1;
                        int day = datePicker.getDayOfMonth();
                        String Start_date = year + "-" + month + "-" + day;
                        SharedPreferencesUtil.putStringSp(this, "Start_date", Start_date);
                        sub.setText(Start_date);
                        dialog1.dismiss();
                        ToastUtil.showToast("重启应用生效");
                    });
                    btn_cancel1.setOnClickListener(v1 -> {
                        SharedPreferencesUtil.removeSp(this, "Start_date");
                        initApp();
                        initWidget();
                        dialog1.dismiss();
                    });
                    break;


                case 2:
                    DialogView.seekBarDialog(this, "设置课程格子高度", "格子高度", "px", (dialog, save, seekBar, seekBarDialog_length) -> {
                        seekBar.setOnSeekBarChangeListener(new AppCompatSeekBar.OnSeekBarChangeListener() {
                            @SuppressLint("SetTextI18n")
                            @Override
                            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                                lattice_length = 100 + progress * 10;
                                seekBarDialog_length.setText(lattice_length + "");
                            }

                            @Override
                            public void onStartTrackingTouch(SeekBar seekBar) {

                            }

                            @Override
                            public void onStopTrackingTouch(SeekBar seekBar) {

                            }
                        });
                        save.setOnClickListener(v -> {
                            SharedPreferencesUtil.putIntSp(this, "lattice_length", lattice_length);
                            dialog.dismiss();
                            EventBus.getDefault().post(new MessageEvent("SubjectFragment", true));
                        });


                    });
                    break;

                case 3:
                    DialogView.seekBarDialog(this, "设置课程节数", "课程节数", "节", (dialog, save, seekBar, seekBarDialog_length) -> {
                        seekBar.setOnSeekBarChangeListener(new AppCompatSeekBar.OnSeekBarChangeListener() {
                            @SuppressLint("SetTextI18n")
                            @Override
                            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                                course_jie = progress + 1;
                                seekBarDialog_length.setText(course_jie + "");
                            }

                            @Override
                            public void onStartTrackingTouch(SeekBar seekBar) {
                            }

                            @Override
                            public void onStopTrackingTouch(SeekBar seekBar) {
                            }
                        });
                        save.setOnClickListener(v -> {
                            SharedPreferencesUtil.putIntSp(this, "course_jie", course_jie);
                            EventBus.getDefault().post(new MessageEvent("SubjectFragment", true));
                            dialog.dismiss();
                        });
                    });
                    break;

                case 4:
                    DialogView.seekBarDialog(this, "时间字体大小", "字体大小", "sp", (dialog, save, seekBar, seekBarDialog_length) -> {
                        seekBar.setOnSeekBarChangeListener(new AppCompatSeekBar.OnSeekBarChangeListener() {
                            @SuppressLint("SetTextI18n")
                            @Override
                            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                                timeSize = progress;
                                seekBarDialog_length.setText(timeSize + "");
                            }

                            @Override
                            public void onStartTrackingTouch(SeekBar seekBar) {
                            }

                            @Override
                            public void onStopTrackingTouch(SeekBar seekBar) {
                            }
                        });
                        save.setOnClickListener(v -> {
                            SharedPreferencesUtil.putIntSp(this, "timeSize", timeSize);
                            EventBus.getDefault().post(new MessageEvent("SubjectFragment", true));
                            dialog.dismiss();
                        });
                    });
                    break;
                case 5:
                    if (EasyPermissions.hasPermissions(this, permissions))
                        UiUtils.startActivity(this, CalendarEventView.class);
                    else new AppSettingsDialog.Builder(this)
                            .setTitle("权限申请")
                            .setRationale("您没有授权应用所需的读写日历的相关权限，此功能无法运行。请打开应用设置以修改应用权限。")
                            .build().show();
                    break;
                case 6:
                    DialogView.seekBarDialog(this, "设置课程格子透明度", "课程格子透明", "%", (dialog, save, seekBar, seekBarDialog_length) -> {
                        seekBar.setOnSeekBarChangeListener(new AppCompatSeekBar.OnSeekBarChangeListener() {
                            @SuppressLint("SetTextI18n")
                            @Override
                            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                                transparency = progress;
                                seekBarDialog_length.setText(transparency * 10 + "");
                            }

                            @Override
                            public void onStartTrackingTouch(SeekBar seekBar) {

                            }

                            @Override
                            public void onStopTrackingTouch(SeekBar seekBar) {

                            }
                        });
                        save.setOnClickListener(v -> {
                            SharedPreferencesUtil.putIntSp(this, "transparency", transparency);
                            EventBus.getDefault().post(new MessageEvent("SubjectFragment", true));
                            dialog.dismiss();
                        });
                    });
                    break;


            }
        });

    }

    public void initWidget() {
        String bg = SharedPreferencesUtil.getStringSp(this, "coursebg_path", null);
        if (bg == null) bg = "设置桌面小部件的背景，默认为透明背景";
        com.dqp.cslggroup.UI.MyListView listView = findViewById(R.id.widget_list);
        List<dakaInfo> infos = new ArrayList<>();
        infos.add(new dakaInfo("背景设置", bg));
        infos.add(new dakaInfo("还原背景", "还原桌面小部件的背景为透明背景"));
        ButtonAdapter arrayAdapter = new ButtonAdapter(infos, Setting.this);
        listView.setAdapter(arrayAdapter);
        listView.setOnItemClickListener((adapterView, view, i, l) -> {
            switch (i) {
                case 0:
                    if (EasyPermissions.hasPermissions(this, permissions)) {
                        Intent intent = new Intent(Intent.ACTION_PICK);
                        intent.setType("image/*");
                        startActivityForResult(intent, 5);
                    } else new AppSettingsDialog.Builder(this)
                            .setTitle("权限申请")
                            .setRationale("您没有授权应用所需的读写手机存储的相关权限，此功能无法运行。请打开应用设置以修改应用权限。")
                            .build().show();
                    break;
                case 1:
                    ToastUtil.showToast("长按还原！");
                    break;
            }
        });

        listView.setOnItemLongClickListener((parent, view, position, id) -> {
            if (position == 1) {
                SharedPreferencesUtil.removeSp(this, "coursebg_path");
                initWidget();
                ToastUtil.showToast("还原成功！请重新在桌面放置小部件！");
            }
            return true;
        });

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == Activity.RESULT_OK && data != null) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = {MediaStore.Images.Media.DATA};
            assert selectedImage != null;
            Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
            assert cursor != null;
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String path = cursor.getString(columnIndex);
            cursor.close();
            SharedPreferencesUtil.putStringSp(this, "bg_path", path);
            initAppSeting();
            initApp();
            initWidget();
            EventBus.getDefault().post(new MessageEvent("MainActivity", 7, null));
        }

        if (requestCode == 2 && resultCode == Activity.RESULT_OK && data != null) {
            Uri selectedImage = data.getData();
            if (Build.VERSION.SDK_INT >= 23) {
                int REQUEST_CODE_CONTACT = 101;
                String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
                for (String str : permissions) {
                    if (this.checkSelfPermission(str) != PackageManager.PERMISSION_GRANTED) {
                        this.requestPermissions(permissions, REQUEST_CODE_CONTACT);
                    }
                }
            }
            cropPic(selectedImage, 3);
        }

        if (requestCode == 3 && resultCode == Activity.RESULT_OK && data != null) {
            Bitmap bitmap;
            try {
                bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uritempFile));
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                Objects.requireNonNull(bitmap).compress(Bitmap.CompressFormat.PNG, 100, baos);
                avatar avatar = new avatar();
                MyApplication.getDaoInstant().getAvatarDao().deleteAll();
                byte[] img = baos.toByteArray();
                avatar.setBytes(img);
                MyApplication.getDaoInstant().getAvatarDao().insertOrReplace(avatar);
                EventBus.getDefault().post(new MessageEvent("MainActivity", 5, null));
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }

        if (requestCode == 4 && resultCode == Activity.RESULT_OK && data != null) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = {MediaStore.Images.Media.DATA};
            assert selectedImage != null;
            Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
            assert cursor != null;
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String path = cursor.getString(columnIndex);
            SharedPreferencesUtil.putStringSp(this, "fm_path", path);
            cursor.close();
        }

        if (requestCode == 5 && resultCode == Activity.RESULT_OK && data != null) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = {MediaStore.Images.Media.DATA};
            assert selectedImage != null;
            Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
            assert cursor != null;
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String path = cursor.getString(columnIndex);
            cursor.close();
            initWidget();
            SharedPreferencesUtil.putStringSp(this, "coursebg_path", path);

        }

    }

    private void cropPic(Uri contentUri, int x) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(contentUri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 0.01);
        intent.putExtra("aspectY", 0.01);
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);
        intent.putExtra("scale", true);
        uritempFile = Uri.parse("file://" + "/" + Environment.getExternalStorageDirectory().getPath() + "/" + "small.jpg");
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uritempFile);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        startActivityForResult(intent, x);
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        if (event.getEvent().equals("Setting")) {
            initApp();
            initWidget();
        }
    }
}
